<template>
  <div>
    <div>
      <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
        <el-breadcrumb-item :to="{ path: '/' }"><i class="el-icon-house" style="font-weight: bold">&nbsp;&nbsp;后台管理</i>
        </el-breadcrumb-item>
        <el-breadcrumb-item><i class="el-icon-s-marketing">&nbsp;&nbsp;部门管理</i></el-breadcrumb-item>
        <el-breadcrumb-item><i class="el-icon-s-order">&nbsp;&nbsp;部门列表</i></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="data-canRead" style="width: 100%;background-color: white;height: auto">
      <el-divider content-position="left">部门查询</el-divider>
      <el-form ref="form">
        <el-row style="vertical-align:bottom;">
          <el-col :span="1">&nbsp;</el-col>
          <el-col :span="8" style="display:inline-block;">
            <el-form-item>
              <span style="font-size: 18px;float: left">搜索部门&nbsp;</span>
              <el-input v-model="inputName" placeholder="请输入部门名称" style="width: 500px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table :data="dept.slice((currentPage-1)*pageSize,currentPage*pageSize)" stripe style="width: 100%">
        <el-table-column prop="id" label="部门ID" width="100px" align="center"></el-table-column>
        <el-table-column prop="name" label="部门名称" width="100px" align="center"></el-table-column>
        <el-table-column prop="description" label="部门简介" width="800px" align="center"></el-table-column>
        <el-table-column prop="sort" label="部门序号" width="150px" align="center"></el-table-column>

        <el-table-column prop="nickname" label="部门经理" width="200px" align="center"></el-table-column>
        <el-table-column label="部门用户" width="200px" fixed="right">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="text"
                style="color:blue"
                @click="getAdmin(scope.row)">查看用户列表
            </el-button>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200px" fixed="right">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="primary"
                circle
                @click="handleEdit( scope.row)"><i class="el-icon-edit" style="color: white"></i>
            </el-button>
            <el-button
                size="mini"
                type="danger"
                circle
                @click="openDeleteConfirm(scope.row)"><i class="el-icon-delete" style="color: white"></i>
            </el-button>
          </template>
        </el-table-column>
        <!--修改部门弹出的对话框-->
        <el-dialog title="编辑部门" :visible.sync="dialogFormVisible" append-to-body>
          <el-form :model="deptForm" :rules="rules" :ref="deptForm">
            <el-form-item label="部门名称" :label-width="formLabelWidth" prop="name">
              <el-input v-model="deptForm.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="部门简介" :label-width="formLabelWidth" prop="description">
              <el-input v-model="deptForm.description" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="部门序号" :label-width="formLabelWidth" prop="sort">
              <el-input v-model="deptForm.sort" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitPermissionFrom()">确 定</el-button>
          </div>
        </el-dialog>
        <!--弹出部门用户列表-->
        <el-dialog title="部门用户列表" :visible.sync="dialogFormVisibles" append-to-body>
          <el-table :data="adminD">
            <el-table-column width="100" property="id" label="用户ID"></el-table-column>
            <el-table-column label="用户头像" width="100px" align="center">
              <template slot-scope="scope">
                <el-avatar :size="50" :src="scope.row.avatar"></el-avatar>
              </template>
            </el-table-column>
            <el-table-column width="150" property="nickname" label="用户昵称"></el-table-column>
            <el-table-column width="300" property="phone" label="用户手机"></el-table-column>
            <el-table-column width="300" property="email" label="用户邮箱"></el-table-column>
            <el-table-column width="500" property="description" label="用户简介"></el-table-column>
          </el-table>
        </el-dialog>
      </el-table>
      <div style="margin-top:15px;">
        <el-pagination align='center' @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page="currentPage"
                       :page-sizes="[1,5,10,20]"
                       :page-size="pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="dept.length">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      adminD: [],
      dialogFormVisibles: false,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      deptOptions: [],
      dept: [],
      deptN: [],
      inputName: '',
      deptForm: {
        name: '',
        description: '',
        sort: '',
      },
      rules: {
        name: [
          {required: true, message: "请输入权限名称", trigger: 'change'},
          {pattern: /([\u4E00-\u9FA5])+/, message: "请输入中文", trigger: 'blur'}
        ],
        description: [
          {required: true, message: "请输入权限简介", trigger: 'change'},
          {
            pattern: /([\u4E00-\u9FA5])+([\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c])*/,
            message: "请输入中文",
            trigger: 'blur'
          }
        ],
        sort: [
          {required: true, message: "请输入权限序号", trigger: 'blur'},
          {pattern: /^[0-9]+$/, message: "请输入数字", trigger: 'blur'}
        ]
      },
      currentPage: 1,
      pageSize: 10,
    }
  },
  methods: {
    /*加载部门*/
    loadDeptNList() {
      let url = 'http://localhost:9090/depts';
      console.log('url = ' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.deptOptions = responseBody.data;
          this.dept = responseBody.data;
          this.deptN = this.dept;
        } else {
          this.$message.error(responseBody.message);
        }
      });
    },
    /*查询部门明细*/
    searchName(keywords) {
      return this.dept.filter(item => {
        if (item.name.includes(keywords)) {
          return item
        }
      })
    },
    /*弹出修改部门窗口*/
    handleEdit(dept) {
      let url = 'http://localhost:9090/depts/' + dept.name;
      console.log('name=' + dept.name);
      console.log('url' + url);

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        let responseBody = response.data;
        console.log('state=' + responseBody.state);
        if (responseBody.state == 20000) {
          this.dialogFormVisible = true;
          this.deptForm = responseBody.data;
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadDeptNList();
            }
          });
        } else {
          this.$message.error(responseBody.message);
        }
      })
    },
    /*修改部门的窗口*/
    submitPermissionFrom() {
      let url = 'http://localhost:9090/depts/' + this.roleForm.id + '/update';
      console.log('url' + url);
      let formData = this.qs.stringify(this.roleForm);
      console.log('formData=' + formData)

      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url, formData).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$message({
            type: 'success',
            message: '修改角色成功!'
          });
          this.dialogFormVisible = false;
          this.loadRoleNList();
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadRoleNList();
            }
          });
        } else {
          this.$message.error(responseBody.message);
        }
      })
    },
    /*弹出部门删除*/
    openDeleteConfirm(dept) {
      let title = '提示';
      let message = '此操作将永久删除【' + dept.name + '】属性, 是否继续?';
      this.$confirm(message, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(dept);
      }).catch(() => {
      });
    },
    /*删除部门弹出的窗口*/
    handleDelete(dept) {
      let url = 'http://localhost:9090/depts/' + dept.id + '/delete';
      console.log('url = ' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$message({
            message: '删除属性【' + dept.name + '】成功！',
            type: 'success'
          });
          this.loadDeptNList();
        } else {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadDeptNList();
            }
          });
        }
      });
    },
    /*查询用户列表*/
    getAdmin(dept) {
      let url = 'http://localhost:9090/depts/' + dept.id + '/list-admin';
      console.log('id=' + dept.id);
      console.log('url = ' + url);
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.adminD = responseBody.data;
          this.dialogFormVisibles = true;
        } else {
          this.$message.error(responseBody.message);
        }
      });
    },
    /*表格*/
    //每页条数改变时触发 选择一页显示多少行
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.currentPage = 1;
      this.pageSize = val;
    },
    //当前页改变时触发 跳转其他页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
    },
  },
  mounted() {
    this.loadDeptNList();
  },
  watch: {
    inputName: function (val) {
      if (val == '') {
        this.dept = this.deptN
      } else {
        this.dept = this.searchName(val)
      }
    }
  }
}
</script>

<style scoped>
* {
  color: black;
}

.data-canRead {
  width: 380px;
  height: 380px;
  margin-top: 15px;
  box-shadow: 0px 5px 5px #8d858a;
  float: left;
  margin-right: 16px;
}

.dept_formSubmit_search {
  width: 200px;
  float: left;
  right: 10px;
  background-color: white;
}

</style>